package com.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class RequestContextUtil {
    /**
     * 获取当前用户 ID（从请求头）
     */
    public static Long getCurrentUserId() {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("无法获取请求上下文");
        }
        HttpServletRequest request = attributes.getRequest();
        String userIdStr = request.getHeader("userId");  //从请求头获取
        if (userIdStr == null) {
            return null;
        }
        return Long.valueOf(userIdStr);
    }

    /**
     * 获取当前用户名（从请求头）
     */
    public static String getCurrentUsername() {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("无法获取请求上下文");
        }
        HttpServletRequest request = attributes.getRequest();
        //从请求头获取
        return request.getHeader("username");
    }
}
